package auth

import (
	"gin-demo/core"
	"gin-demo/sysinit"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

// UserService 用户服务
type UserService struct {
}

// GetByID 通过用户ID获取用户
func (s UserService) GetByID(id interface{}) (user User, ok bool) {
	ok = !sysinit.DB.First(&user, id).RecordNotFound()
	return user, ok
}

// GetByUsername 通过用户名获取用户
func (s UserService) GetByUsername(username string) (user User, ok bool) {
	ok = !sysinit.DB.Where("username = ?", username).First(&user).RecordNotFound()
	return user, ok
}

// Create 创建用户
func (s UserService) Create(form UserCreateForm) (user User, err error) {
	user = User{Username: form.Username, Password: form.Password}
	err = sysinit.DB.Create(&user).Error
	return
}

// Update 更新用户
func (s UserService) Update(user *User, updateMap gin.H) (err error) {
	if pwd, ok := updateMap["password"].(string); ok {
		if updateMap["password"], err = core.EncryptPassword(pwd); err != nil {
			return err
		}
	}
	return sysinit.DB.Model(user).Update(updateMap).Error
}

// QuerySet 查询用户
func (s UserService) QuerySet(query string) *gorm.DB {
	query = "%" + query + "%"
	return sysinit.DB.Where("username LIKE ?", query).Order("username")
}
